package com.neighbor.neighborhooduser.utils;

import com.alibaba.fastjson.JSON;
import com.neighbor.neighborhooduser.pojo.Users;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ReOpe {

    @Autowired
    RedisUtils redisUtils;

    /**
     *          验证请求中用户信息是否过期或是否登录
     * @param request   请求体
     * @return  是否请求成功，请求用户对象
     */
    public ResponseMsg IsToken(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR,"未提供认证token");
        }
        Claims claims = JwtUtils.parseJWT(token);
        Users user = JSON.parseObject(claims.getSubject(), Users.class);
        try {
            if(!redisUtils.hasKey(user.getUserId().toString())){
                throw new Exception("登录已过期");
            }
            if(!redisUtils.get(user.getUserId().toString()).equals(token)){
                throw new Exception("token错误");
            }
        }catch (Exception e){
            return ResponseMsg.getInstance(ResponseMsg.TOKEN_ERROR,e.getMessage());
        }
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"验证用户token成功",user);
    }


}
